# -*- coding: iso-8859-2 -*-

import email
import os
import logging
import traceback
import re
import string
import quopri

from authorshipanalyzer.message import Message
from authorshipanalyzer.message.parser import Parser
from authorshipanalyzer.logger import GlobalLogger

logger = GlobalLogger.getLogger()

class ParserEarly(Parser):
    '''
    Parser for info1 messages in the old type
    format compliant to RFC934
    '''
       
    def retrieveMessages(self, filename):
        '''
        Function retrieving messages from a given filename
        @param filename: path to the file with messages 
        '''
        logger.info("Retrieving: " + filename)
       
        inMessage = False
       
        try:
            file = open(filename, "r")
            
            message = Message()
            text = ""
            
            for line in file.readlines():
                line = str(line).strip()

                if inMessage == True:
                    if re.match("^From daemon", line) != None:
                        continue
                    
                    if re.match("^From:", line) != None:
                        author = self.parseAuthorLine(line)
                        message.setAuthor(author)
                        
                        address = self.parseAddressLine(line)
                        message.setAddress(address)
                        continue
                    
                    if re.match("^Subject:", line) != None:
                        subject = self.parseSubjectLine(line)
                        message.setSubject(subject)
                        continue
                    
                    if re.match("^Date:", line) != None:
                        date = email.utils.parsedate(line[5:])  
                        if date == None:
                            date = self._setApproximateDate(message, filename)
                        else:
                            message.setDate(date)
                        continue
                
                if re.match("------- THIS IS A RFC934 COMPLIANT DIGEST, YOU CAN BURST IT -------", line) != None \
                    or re.match("------- CUT --- CUT --- CUT --- CUT --- CUT --- CUT --- CUT -------", line) != None:
                    if inMessage == False:
                        inMessage = True
                    else:
                        message.setText(text)
                        self._appendToMessages(message)
                        message = Message()
                        text = ""
                elif inMessage == True:
                    text += line +"\n"

        except IOError:
            print_exc()
        finally:
            file.close()  
    
    def parseAuthorLine(self, line):
        '''
        @return: author name
        '''
        line = line[6:]
        
        result = ""
        for word in str(line).split():
            if re.match(".*@.*", word) == None:
                word = str(word).replace("()", '')
                result += word + " "
            
        return result.strip()
    
    def parseAddressLine(self, line):
        '''
        @return: email address
        '''
        line = line[6:]
        
        for word in str(line).split():
            if re.match(".*@.*", word) != None:
                return word.strip()
            
        return None
    
    def parseSubjectLine(self, line):
        '''
        @return: subject of the message
        '''
        line = line[9:]

        while (re.match("^(Re:|Odp:)", line, re.IGNORECASE) != None):
            if re.match("^Re:", line, re.IGNORECASE):
                line = line[3:].strip()
            else:
                line = line[4:].strip()
                    
        return line.strip()
    
if __name__ == "__main__":
    from authorshipanalyzer.file import Path
    
    parser = ParserEarly()
    parser.retrieveMessages(Path.getMainDir() + os.sep + "info1" + os.sep + "info1.1996-01")
    messages = parser.getMessageList()
    print len(messages)
    
    for message in messages:
        message.printInfo()